<?php

namespace App\Service;

use Illuminate\Support\Facades\Redis;
use Mrgoon\AliSms\AliSms;
use App\Models\SmsLog;

/**
 * 阿里云短信类
 */
class AliyunSms
{
    /**
     * 发送短信验证码
     */
    public static function SendSms(int $phone, array $params = [])
    {
        try {
            $SmsLog = new SmsLog();
            $ali_sms = new AliSms();
            $code = $params['code'];
            $result = $ali_sms->sendSms($phone, $params);
            /**
             * $result = [
             * 'Message'=> '触发小时级流控Permits:5',
             * 'RequestId' => '2F8EBEAC-1996-508A-B769-396B777AA422',
             * 'Code' => 'isv.BUSINESS_LIMIT_CONTROL'
             * ];
             */
            if ($result->Code == "OK") {
                //已经发送
                $status = SmsLog::STATUS_SEND;
            } else {
                //未发送
                $status = SmsLog::STATUS_FAIL;
            }
            $SmsLog->createLog($phone, $code, $status, \GuzzleHttp\json_encode($result));
            return $result;
        } catch (\Throwable $e) {
            throw new \Exception($e->getMessage());
        }
    }

    //工作室审核通过短信通知
    public function sendMessage(int $phone, array $params = [], int $type)
    {
        try {
            $SmsLog = new SmsLog();
            $result = AliSms::sendMessage($phone, $params, $type);
            /**
             * $result = [
             * 'Message'=> '触发小时级流控Permits:5',
             * 'RequestId' => '2F8EBEAC-1996-508A-B769-396B777AA422',
             * 'Code' => 'isv.BUSINESS_LIMIT_CONTROL'
             * ];
             */
            if ($result->Code == "OK") {
                //已经发送
                $status = SmsLog::STATUS_SEND;
            } else {
                //未发送
                $status = SmsLog::STATUS_FAIL;
            }
            $SmsLog->createWorklog($phone, 10011, $status, \GuzzleHttp\json_encode($result));
            return $result;
        } catch (\Throwable $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 检查当前手机号发送频率
     */
    public static function CheckRate($phone): bool
    {
        /**
         * //这里key在.env文件定义的
         * $key = 'REDIS_EXPIRED_TIME';
         * if (Redis::exists($key . $phone)) {
         * return true;
         * } else {
         * return false;
         * }
         */
        /**
         * $SmsLog = new SmsLog();
         * $result = $SmsLog->checkRate($phone);
         * $now = time();
         * if ($result) {
         * if (($now - strtotime($result->created_at)) < SmsLog::SEND_INTERVAL_TIME) {
         * return false;
         * }
         * }
         * return true;
         */
    }
}
